<template>
    <div>
        <Category :show="show" />
        <el-card class="box-card">
            <div v-show="show == 0">
                <el-button icon="Plus" type="primary" @click="add"
                    :disabled="categoryStore.c3Id ? false : true">添加属性</el-button>
                <el-table :data="tableData" border style="margin: 10px 0;">
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="attrName" label="属性名称" align="center" width="180" />
                    <el-table-column label="属性值名称">
                        <template #="{ row, $index }">
                            <el-tag style="margin: 0 6px;" v-for="item in row.attrValueList" :key="item.id">{{
                                item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="address" label="属性操作" align="center" width="150">
                        <template #="{ row, $index }">
                            <el-button icon="edit" type="primary" size="small" @click="edit(row)"></el-button>
                            <el-button icon="delete" type="danger" size="small" @click="DeleteAttr(row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div v-show="show == 1">
                <el-form :inline="true">
                    <el-form-item label="属性名称">
                        <el-input v-model="attrParams.attrName" placeholder="请输入属性名称"></el-input>
                    </el-form-item>
                </el-form>
                <el-button :disabled="attrParams.attrName ? false : true" type="primary" @click="addValue"
                    icon="plus">添加属性</el-button>
                <el-button size="default" @click="cancel">取消</el-button>
                <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
                    <el-table-column label="序号" width="80" type="index" align="center"></el-table-column>
                    <el-table-column label="属性值" align="center">
                        <template #="{ row, $index }">
                            <el-input size="small" :ref="(vc: any) => input[$index] = vc" v-if="row.flag"
                                @blur="look(row, $index)" placeholder="请输入属性值名称" v-model="row.valueName"></el-input>
                            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template #="{ row, $index }">
                            <el-button type="danger" size="small" @click="attrParams.attrValueList.splice($index, 1)"
                                icon="delete"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="save"
                    :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
                <el-button size="default" @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import Category from '@/components/Category/index.vue'
import useCategoryStore from '@/store/modules/category'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage, ElMessageBox } from 'element-plus'

let categoryStore = useCategoryStore()
let tableData = ref<Attr[]>([])
let show = ref<number>(0)
let input = ref<any>([])
let attrParams = reactive<Attr>({
    attrName: "",
    attrValueList: [],
    categoryId: "",
    categoryLevel: 3,
})

watch(() => categoryStore.c3Id, () => {
    tableData.value = []
    if (!categoryStore.c3Id) return;
    load()
})

const load = async () => {
    const { c1Id, c2Id, c3Id } = categoryStore
    let res: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
    if (res.code == 200) {
        tableData.value = res.data
    }
}

const add = () => {
    Object.assign(attrParams, {
        attrName: "",
        attrValueList: [],
        categoryId: "",
        categoryLevel: 3,
    })
    show.value = 1
    attrParams.categoryId = categoryStore.c3Id
}
const addValue = () => {
    attrParams.attrValueList.push({
        valueName: '',
        flag: true    //编辑模式的切换
    })
    nextTick(() => {
        input.value[attrParams.attrValueList.length - 1].focus()
    })
}
const edit = (row: Attr) => {
    show.value = 1
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
const DeleteAttr = (row: any) => {
    ElMessageBox.confirm(
        `你确定要删除属性${row.attrName}吗?`,
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await reqRemoveAttr(row.id)
            if (result.code == 200) {
                //删除成功提示信息
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                });
                //再次获取已有的数据
                load()
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败'
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消成功',
            })
        })
}
const cancel = () => {
    show.value = 0
}
const save = async () => {
    let res: any = await reqAddOrUpdateAttr(attrParams)
    if (res.code == 200) {
        show.value = 0
        ElMessage({
            type: 'success',
            message: attrParams.id ? '修改成功' : '添加成功'
        });
        load()
    } else {
        ElMessage({
            type: 'error',
            message: attrParams.id ? '修改失败' : '添加失败'
        });
    }
}
const look = (row: AttrValue, $index: number) => {
    if (row.valueName.trim() == '') {
        attrParams.attrValueList.splice($index, 1)
        ElMessage({
            type: 'warning',
            message: '属性值不能为空'
        })
        return
    }

    //非法情况2
    let repeat = attrParams.attrValueList.find((item) => {
        //切记把当前失却焦点属性值对象从当前数组扣除判断
        if (item != row) {
            return item.valueName === row.valueName;
        }
    });

    if (repeat) {
        //将重复的属性值从数组当中干掉
        attrParams.attrValueList.splice($index, 1);
        //提示信息
        ElMessage({
            type: 'warning',
            message: '属性值不能重复'
        })
        return;
    }
    row.flag = false
}
const toEdit = (row: AttrValue, $index: number) => {
    row.flag = true
    nextTick(() => {
        input.value[$index].focus()
    })
}

onBeforeUnmount(() => {
    categoryStore.$reset()
})
</script>

<style scoped lang="scss">
.box-card {
    margin: 10px 0;
}
</style>